package com.numberone.master.modules.orders.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.numberone.master.common.persistence.Page;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.common.utils.DoubleUtil;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.modules.card.entity.Card;
import com.numberone.master.modules.card.service.CardService;
import com.numberone.master.modules.orders.entity.RechargeOrder;
import com.numberone.master.modules.orders.entity.ShareOrder;
import com.numberone.master.modules.orders.service.RechargeOrderService;
import com.numberone.master.modules.orders.service.ShareOrderService;
import com.numberone.master.modules.profit.entity.AccountInfo;
import com.numberone.master.modules.profit.service.AccountInfoService;
import com.numberone.master.modules.sys.dao.OfficeCardDao;
import com.numberone.master.modules.sys.entity.OfficeCard;
import com.numberone.master.modules.sys.utils.UserUtils;

/**
 * 充值流水订单Controller
 * @author ck
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${adminPath}/orders/rechargeOrder")
public class RechargeOrderController extends BaseController {

	@Autowired
	private RechargeOrderService rechargeOrderService;
	
	@Autowired
	private OfficeCardDao officeCardDao;
	
	@Autowired
	private ShareOrderService shareOrderService;
	
	@Autowired
	private CardService cardService;
	
	@Autowired
	private AccountInfoService accountInfoService;

	 /**
     * 根据id查询一条数据
     * @param id
     * @return
     */
	@ModelAttribute
	public RechargeOrder get(@RequestParam(required=false) String id) {
		RechargeOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = rechargeOrderService.get(id);
		}
		if (entity == null){
			entity = new RechargeOrder();
		}
		return entity;
	}

	 /**
     * list充值流水列表
     * @param rechargeOrder
     * @param request
     * @param response
     * @param model
     * @return
     */
	@RequiresPermissions("orders:rechargeOrder:list")
	@RequestMapping(value = {"list", ""})
	public String list(RechargeOrder rechargeOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		String officeId = UserUtils.getUser().getOffice().getId();
		if(!StringUtils.equals("1", officeId)){
			rechargeOrder.setOfficeId(officeId);
		}
		Page<RechargeOrder> page = rechargeOrderService.findPage(new Page<RechargeOrder>(request, response), rechargeOrder); 
		model.addAttribute("page", page);
		return "modules/orders/rechargeOrderList";
	}

	/**
	 * 审核列表
	 * @param rechargeOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("orders:examine:list")
	@RequestMapping(value = {"examineList", ""})
	public String examineList(RechargeOrder rechargeOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		rechargeOrder.setRechargeState("1");
		rechargeOrder.setPayState("2");
		Page<RechargeOrder> page = rechargeOrderService.findPage(new Page<RechargeOrder>(request, response), rechargeOrder); 
		model.addAttribute("page", page);
		return "modules/orders/examineList";
	}

	/**
	 * 审核充值
	 * @param id 主键
	 * @param rechargeState 订单那状态
	 * @param rechargeOrderNo 内部订单号
	 * @return
	 */
	@RequiresPermissions("orders:examine:examine")
	@RequestMapping(value = "examine")
	public String examine(String id,String rechargeState,String rechargeOrderNo,RedirectAttributes redirectAttributes) {
		RechargeOrder o = rechargeOrderService.get(id);
		if(o == null){
			addMessage(redirectAttributes, "审核失败！未查询到充值流水。");
			return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
		}
		if(StringUtils.equals("1", o.getPayState())){
			addMessage(redirectAttributes, "审核失败！此订单还未支付。");
			return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
		}
		if(StringUtils.equals("3", o.getRechargeState()) || StringUtils.equals("2", o.getRechargeState())){
			addMessage(redirectAttributes, "审核失败！此订单已经审核过。");
			return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
		}
		RechargeOrder rechargeLs = new RechargeOrder();
		rechargeLs.setId(id);
		rechargeLs.setRechargeTime(new Date());
		rechargeLs.setRechargeState(rechargeState);
		rechargeLs.setRechargeOrderNo(rechargeOrderNo);
		rechargeOrderService.update(rechargeLs);
		if(StringUtils.equals(rechargeState, "2")){
			//审核成功添加分润信息
			Card card = cardService.getCardInfoByCCID(o.getIccid());
			insertShare(card.getId(),card.getIccid(), o.getOfficeId(),Double.valueOf(o.getMoney()), o.getMoney(), o.getOrderNo(),o.getPkg(),o.getPkgType());
		}
		addMessage(redirectAttributes, "审核成功。");
		return "redirect:"+adminPath+"/orders/rechargeOrder/examineList?repage";
	}
	
	
	/**
	 * 批量审核
	 * @param id 主键
	 * @param rechargeState 订单那状态
	 * @param rechargeOrderNo 内部订单号
	 * @return
	 */
	@RequiresPermissions("orders:examine:examine")
	@RequestMapping(value = "batchExamine")
	public String batchExamine(String[] ids,RedirectAttributes redirectAttributes) {
		if(ids.length == 0){
			addMessage(redirectAttributes, "未选择数据审核。");
			return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
		}
		for (int i = 0; i < ids.length; i++) {
			RechargeOrder o = rechargeOrderService.get(ids[i]);
			if(o == null){
				addMessage(redirectAttributes, "审核失败！未查询到充值流水。");
				return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
			}
			if(StringUtils.equals("1", o.getPayState())){
				addMessage(redirectAttributes, "审核失败！此订单还未支付。");
				return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
			}
			if(StringUtils.equals("3", o.getRechargeState()) || StringUtils.equals("2", o.getRechargeState())){
				addMessage(redirectAttributes, "审核失败！此订单已经审核过。");
				return "redirect:" + adminPath + "/orders/rechargeOrder/examineList?repage";
			}
			RechargeOrder rechargeLs = new RechargeOrder();
			rechargeLs.setId(ids[i]);
			rechargeLs.setRechargeTime(new Date());
			rechargeLs.setRechargeState("2");
			rechargeLs.setRechargeOrderNo("0000");
			rechargeOrderService.update(rechargeLs);
			//审核成功添加分润信息
			Card card = cardService.getCardInfoByCCID(o.getIccid());
			insertShare(card.getId(),card.getIccid(), o.getOfficeId(),Double.valueOf(o.getMoney()), o.getMoney(), o.getOrderNo(),o.getPkg(),o.getPkgType());
		}
		addMessage(redirectAttributes, "成功审核<"+ids.length+">条数据");
		return "redirect:"+adminPath+"/orders/rechargeOrder/examineList?repage";
	}
	
	/**
	 * 添加分润信息
	 * @param cardId
	 * @param officeId
	 */
	public void insertShare(String cardId,String iccid,String officeId,Double price,String totalPrice,String orderNo,String pkgName,String pkgType){
		String id = UserUtils.getUser().getOffice().getId();
		OfficeCard officeCard = officeCardDao.selectShare(cardId, officeId,pkgType);
		if(officeCard != null){
			//查询上一级的人信息
			OfficeCard c = officeCardDao.selectUpperLevel(cardId, officeCard.getOfficeId());
			ShareOrder shareOrder = new ShareOrder(); 
			shareOrder.setCreateById(id);
			shareOrder.setCreateDate(new Date());
			shareOrder.setUpdateById(id);
			shareOrder.setRemarks(pkgName);
			shareOrder.setUpdateDate(new Date());
			shareOrder.setIccid(cardId);
			shareOrder.setTotalAmount(totalPrice);
			if(c != null){
				shareOrder.setSuperiorOfficeId(c.getOfficeId());
			}else{
				shareOrder.setSuperiorOfficeId("0");
			}
			shareOrder.setCostAmount(officeCard.getPrice());//成本价格
			Double shareAmount = DoubleUtil.sub(price,Double.valueOf(officeCard.getPrice()));
			//判断是否为负的
			
			shareOrder.setShareAmount(String.valueOf(shareAmount));//分润金额
			shareOrder.setOrderNo(orderNo);
			shareOrder.setOfficeId(officeId);
			shareOrder.setPkgType(Long.valueOf(officeCard.getPkg()));
			shareOrderService.insert(shareOrder);
			//增加个人金额
			AccountInfo account = accountInfoService.getAccountByOfficeId(officeId);
			if(account != null){
				Double zamt = Double.valueOf(account.getZamt());
				Double kamt = Double.valueOf(account.getKamt());
				account.setZamt(String.valueOf(DoubleUtil.add(zamt, shareAmount)));
				account.setKamt(String.valueOf(DoubleUtil.add(kamt, shareAmount)));
				accountInfoService.update(account);
			}
			if(c != null){
				insertShare(cardId, iccid,c.getOfficeId(), Double.valueOf(officeCard.getPrice()), totalPrice, orderNo,pkgName,pkgType);
			}
		}
	}
	
	/**
	 * 查询卡号
	 * @param iccid
	 * @return
	 */
	@RequestMapping(value = {"getNumberByIccid", ""})
	@ResponseBody
	public String getNumberByIccid(String iccid){
		Card card = cardService.getCardInfoByCCID(iccid);
		return card.getPhonenumber();
	}
}